package org.wombat.service.framework.customs.springframework.context.support;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.wombat.util.SystemConstants;

import java.util.Locale;

/**
 * Created by IntelliJ IDEA.
 * User: rovsipet
 * Date: 24-11-2010
 * Time: 11:02:57
 * To change this template use File | Settings | File Templates.
 */
public class CustomReloadableResourceBundleMessageSource extends ReloadableResourceBundleMessageSource {

    public void setBasenames(String[] names){
        String systemPath = loadSystemPath();

        for (int i = 0 ; i < names.length ; i++ )
            names[i] = buildFilePath(names[i],systemPath).toString();

        super.setBasenames(names);
    }

    /**
     * Loads the system path from the local system environment.
     * The result can varie depending on the local system.
     *
     * Windows system environments are case insensitive but the unix or linux core is not.
     * The method tries to locate the system environment variable with upperCase letters only and lowerCase only.
     * If this does not succeed then a null string is returned
     * @return
     */
    private String loadSystemPath() {
        String systemPath = System.getenv(SystemConstants.SYSTEM_ENVIRONMENT_NAME);
        if(systemPath == null)
            systemPath = System.getenv(SystemConstants.SYSTEM_ENVIRONMENT_NAME).toLowerCase(Locale.getDefault());
        return systemPath;
    }

    /**
     * Builds an url for a file.
     *
     * e.g. "file:/foo/bar/file.extension"
     * @param filename - the full filename
     * @param systemPath - the full system path on the local system 
     * @return
     */
    private StringBuilder buildFilePath(String filename, String systemPath) {
        StringBuilder filePath = new StringBuilder("file:");
        filePath.append(systemPath);

        char lastChar = filePath.charAt(filePath.length() -1);
        boolean endsWithSlashValue = lastChar == '/' || lastChar == '\\';

        if(endsWithSlashValue)
            filePath.append(filename);
        else
            filePath.append('/').append(filename);

        return filePath;
    }

}
